import random
import mysql.connector

# 创建MySQL数据库连接
conn = mysql.connector.connect(
    host='localhost',
    user='root',
    password='Bing2310',
    database='mylife'
)

# 创建游标对象
cursor = conn.cursor()

# 查询数据库中的记录
query = "SELECT id FROM music_musicdetails"  # 假设你的表名为music_musicdetails
cursor.execute(query)

# 获取查询结果
results = cursor.fetchall()

# 遍历每个记录并更新rating字段
for row in results:
    music_id = row[0]
    random_rating = random.randint(1, 5)  # 生成1到5之间的随机整数

    # 更新记录的rating字段
    update_query = "UPDATE music_musicdetails SET rating = %s WHERE id = %s"
    cursor.execute(update_query, (random_rating, music_id))

# 提交更改并关闭连接
conn.commit()
cursor.close()
conn.close()

print("所有记录的rating字段已更新并保存到数据库。")
